const db = require("../db/index");
const moment = require('moment')

// 就诊卡号生成
function generateRandomNumber() {
    // 生成首位数字（1-9）
    const firstDigit = Math.floor(Math.random() * 9) + 1;

    // 生成接下来的三位数字（年份部分）
    const year = Math.floor(Math.random() * 1000);

    // 生成月份（01-12）
    const month = String(Math.floor(Math.random() * 12) + 1).padStart(2, '0');

    // 生成最后两位随机数字
    const randomEnd = Math.floor(Math.random() * 100);

    // 组合成最终的字符串，确保长度为8位
    const result = `${firstDigit}${String(year).padStart(3, '0')}${month}${String(randomEnd).padStart(2, '0')}`;
    
    return result;
}

// 病历号生成
function medicalrecord() {
    let result = '';

    // 首位数字不能是0，所以随机选择1-9之间的一个数字
    result += Math.floor(Math.random() * 9) + 1;

    // 剩下的9位可以是0-9之间的任意数字
    for (let i = 0; i < 9; i++) {
        result += Math.floor(Math.random() * 10);
    }

    return result;
}

// 姓名生成
function generateRandomChineseName() {
    // 常用姓氏列表
    const surnames = ['李', '王', '张', '刘', '陈', '杨', '赵', '黄', '周', '吴'];

    // 常用名字字符列表
    const givenNames = ['伟', '芳', '娜', '敏', '静', '丽', '强', '磊', '军', '洋', '勇', '杰'];

    // 随机选择一个姓氏
    const surname = surnames[Math.floor(Math.random() * surnames.length)];

    // 决定名字的长度，总长度最多为4个字，姓氏占1个，所以名字长度为0到3个字
    const maxLength = 3 - surname.length; // 通常为3，因为surname长度为1
    const nameLength = Math.floor(Math.random() * maxLength) + 1; // 名字长度为1到3

    let givenName = '';
    for (let i = 0; i < nameLength; i++) {
        // 随机选择一个名字字符
        const randomIndex = Math.floor(Math.random() * givenNames.length);
        givenName += givenNames[randomIndex];
    }

    // 组合姓氏和名字
    const fullName = surname + givenName;

    // 如果名字长度超过4（理论上不会发生，因为计算时限制了），则截断或调整逻辑
    // 此处假设逻辑正确，不需要额外截断

    return fullName;
}


// 忘记密码
exports.appforget = (req, res) => {
    var sql =
        "select * from applogin where phone="+req.query.phone;
    db.query(sql, [], (err, data) => {
        if (err) {
            console.log("出错了", err);
            return res.send("错误" + err.message);
        }else{
            if(data.length==0){
                res.send({
                    state:404
                })
            }else{
                res.send({
                    data,
                    state:200
                })
            }
        }
    });
};
// 修改密码
exports.appchange = (req, res) => {
    var sql =
        `update applogin set password = '${req.body.passward}' where user_id = ${req.body.userid}`;
    db.query(sql, [], (err, data) => {
        if (err) {
            console.log("出错了", err);
            return res.send("错误" + err.message);
        }else{
            res.send({
                data,
                state:200
            })
        }
    });
};
// 查询
exports.appuserlists = (req, res) => {
    var sql =
        "select * from applogin where phone="+req.body.phone;
    db.query(sql, [], (err, data) => {
        if (err) {
            console.log("出错了", err);
            return res.send("错误" + err.message);
        }else{
            // 未注册进行注册
            console.log(data)
            if (data.length==0) {
                var sql =
                    `insert into applogin(Medical_number,phone,name) value(${generateRandomNumber()},'${req.body.phone}','${generateRandomChineseName()}')`;
                db.query(sql, [], (err, datas) => {
                    if (err) {
                        console.log("出错了", err);
                        return res.send("错误" + err.message);
                    }
                    console.log(datas)
                    res.send({
                        datas,
                        state: 404
                    })
                });
    
            } else {
                // 已注册进行登录
                res.send({
                    data,
                    state: 200
                });
            }
        }
        
        
    });
};

// 密码登录查询
exports.appuserpsw = (req, res) => {
    var sql =
        `select * from applogin where phone=${req.body.phone} and password="${req.body.passward}"`;
    db.query(sql, [], (err, data) => {
        if (err) {
            console.log("出错了", err);
            return res.send("错误" + err.message);
        }else{
            if(data.length==0){
                res.send({
                    state:404
                })
            }else{
                res.send({
                    data,
                    state:200
                })
            }
        }
    });
};



// 用户挂号
exports.appregisterlist = (req, res) => {
    const { userID , memberid , name ,depart , price , dates , farewell} = req.body
    // 根据userID查询就诊卡号、姓名
   var sql =
        `select * from ${memberid==0?'applogin':'family'}  where ${memberid==0?'user_id='+userID:'member_id='+memberid}`;
    db.query(sql, [], (err, data) => {
        if (err) {
            console.log("出错了", err);
            return res.send("错误" + err.message);
        }else{
            var sql =
                `select * from patient where Medicalcard='${data[0].Medical_number}' and name="${data[0].name}"`;
            db.query(sql, [], (err, request) => {
                if (err) {
                    console.log("出错了", err);
                    return res.send("错误" + err.message);
                } else {
                    // 在患者登记的表中未查询到相关信息 ，新增患者信息
                    if(request.length==0){
                        var sql =
                            `insert into patient(Medicalrecord,Medicalcard,name,sex,IDtype,Idcard,status,age,phone,address,nowDetail,relotion,people,guardianshipphone,Patientnature) value('${medicalrecord()}','${data[0].Medical_number}','${data[0].name}','${data[0].sex}','${data[0].IDtype}','${data[0].idcard}','正常',${data[0].age},'${data[0].phone}','${data[0].current_address}','${data[0].address}','${data[0].relotion}','${data[0].people}','${data[0].guardianshipphone}','自费')`;
                        db.query(sql, [], (err, datas) => {
                            if (err) {
                                console.log("出错了", err);
                                return res.send("错误" + err.message);
                            }else{
                                var sql =
                                    `INSERT INTO registerlist(Medicalcard,Medicalrecord,name,department,doctor,money,status,date,timestamp,patient_id)VALUES('${data[0].Medical_number}','${medicalrecord()}','${data[0].name}','${depart}','${name}',${price},'待就诊','${dates.year + '-' + (dates.month < 10 ? '0' + dates.month : dates.month) + '-' + (dates.day < 10 ? '0' + dates.day : dates.day )+ ' ' + (farewell == '上午' ? '8:00-12:00' : '14:00-18:00')}','${moment(new Date()).format("YYYY-MM-DD HH:mm:ss")}',${datas.insertId})`;
                                db.query(sql, [], (err, data) => {
                                    if (err) {
                                        console.log("出错了", err);
                                        return res.send("错误" + err.message);
                                    }
                                    res.send({
                                        state: 200
                                    });
                                });
                            }
                        });
                    }else{
                        var sql =
                            `INSERT INTO registerlist(Medicalcard,Medicalrecord,name,department,doctor,money,status,date,timestamp,patient_id)VALUES('${data[0].Medical_number}','${medicalrecord()}','${data[0].name}','${depart}','${name}',${price},'待就诊','${dates.year + '-' + (dates.month < 10 ? '0' + dates.month : dates.month) + '-' + (dates.day < 10 ? '0' + dates.day : dates.day )+ ' ' + (farewell == '上午' ? '8:00-12:00' : '14:00-18:00')}','${moment(new Date()).format("YYYY-MM-DD HH:mm:ss")}',${request[0].patient_id})`;
                        db.query(sql, [], (err, data) => {
                            if (err) {
                                console.log("出错了", err);
                                return res.send("错误" + err.message);
                            }
                            res.send({
                                state: 200
                            });
                        });
                    }
                }
            });
        }
        
    });
    
};
// 挂号成功医生对应号源数量-1
exports.schecusreduce = (req, res) => {
    const { docID , dateID , farewell } = req.body
    var sql =
        `select * from schedutime where doctor_id=${docID} and dates_id=${dateID}`;
    db.query(sql, [], (err, data) => {
        if (err) {
            console.log("出错了", err);
            return res.send("错误" + err.message);
        }else{
            var sql =
                `update schedutime set ${farewell=='上午'?data[0].timeFour>0?'timeFour':data[0].timeThree>0?'timeThree':data[0].timeTwo>0?'timeTwo':'timeOne':data[0].timeEight>0?'timeEight':data[0].timeSeven>0?'timeSeven':data[0].timeSix>0?'timeSix':'timeFive'}= ${farewell=='上午'?data[0].timeFour>0?'timeFour':data[0].timeThree>0?'timeThree':data[0].timeTwo>0?'timeTwo':'timeOne':data[0].timeEight>0?'timeEight':data[0].timeSeven>0?'timeSeven':data[0].timeSix>0?'timeSix':'timeFive'}-1 where TimeCount_id = ${data[0].TimeCount_id}`;
            db.query(sql, [], (err, datas) => {
                if (err) {
                    console.log("出错了", err);
                    return res.send("错误" + err.message);
                } else {
                    res.send({
                        datas,
                        state:200
                    })
                }
            });
        }
    });
};

// 根据用户id查询个人信息
exports.appselectid = (req, res) => {
    var sql =
        "select * from applogin where user_id="+req.query.userid;
    db.query(sql, [], (err, data) => {
        if (err) {
            console.log("出错了", err);
            return res.send("错误" + err.message);
        }else{
            res.send({
                data,
                state:200
            })
        }
    });
};
// 查询用户家庭成员
exports.appfamily = (req, res) => {
    var sql =
        "select * from family where user_id="+req.query.userid;
    db.query(sql, [], (err, data) => {
        if (err) {
            console.log("出错了", err);
            return res.send("错误" + err.message);
        }else{
            res.send(data)
        }
    });
};


// 注册用户添加数据
exports.appregister = (req, res) => {
    const { name , age , sex , IDtype , idcard , current_address , address ,  relotion , people , guardianshipphone , userid} = req.body
    var sql =
        `update applogin set name='${name}' , age=${age} , sex='${sex}' , IDtype='${IDtype}' , idcard='${idcard}' , current_address="${current_address.join(',')}",address="${address}", relotion="${relotion}", people='${people}', guardianshipphone="${guardianshipphone}" where user_id=${userid}`;
    db.query(sql, [], (err, data) => {
        if (err) {
            console.log("出错了", err);
            return res.send("错误" + err.message);
        }else{
            res.send({
                data,
                state:200
            })
        }
    });
};

// 添加就诊人家庭
exports.appfamilyadd = (req, res) => {
    const { name , phone , age , sex , IDtype , idcard , current_address , address , relationship , userid} = req.body
    var sql =
        `insert into family(name,Medical_number,phone,age,sex,IDtype,idcard,current_address,address,relotion,user_id) value('${name}',${generateRandomNumber()},'${phone}',${age},'${sex}','${IDtype}', '${idcard}','${current_address.join(',')}', '${address}','${relationship}',${userid})`;
    db.query(sql, [], (err, data) => {
        if (err) {
            console.log("出错了", err);
            return res.send("错误" + err.message);
        }else{
            res.send({
                data,
                state:200
            })
        }
    });
};

// 查询挂号订单
exports.appregisterinfo = (req,res) =>{
    var sql =
        "select * from applogin where user_id="+req.query.userid;
    db.query(sql, [], (err, data) => {
        if (err) {
            console.log("出错了", err);
            return res.send("错误" + err.message);
        }else{
            var sql =
                `select * from patient where Medicalcard=${data[0].Medical_number} and name = '${data[0].name}'`;
            db.query(sql, [], (err, datas) => {
                if (err) {
                    console.log("出错了", err);
                    return res.send("错误" + err.message);
                } else {
                    var sql =
                        "select * from registerlist where patient_id=" + datas[0].patient_id;
                    db.query(sql, [], (err, dataes) => {
                        if (err) {
                            console.log("出错了", err);
                            return res.send("错误" + err.message);
                        } else {
                            res.send({
                                dataes,
                                state:200
                            })
                        }
                    });
                }
            });
            
        }
    });
}
// 取消挂号订单
exports.appregisterconcel = (req,res) => {
    var sql =
        "update registerlist set status = '已取消' where register_id=" + req.body.register_id;
    db.query(sql, [], (err, data) => {
        if (err) {
            console.log("出错了", err);
            return res.send("错误" + err.message);
        } else {
            res.send({
                data,
                state:200
            })
        }
    });
}

// 查询门诊缴费列表
exports.apppayfrees = ( req,res ) => {
    const { memberid , userid } = req.query
    var sql =
        `select * from ${memberid==0?'applogin':'family'} where ${memberid==0?'user_id='+userid:'member_id='+memberid}`;
    db.query(sql, [], (err, data) => {
        if (err) {
            console.log("出错了", err);
            return res.send("错误" + err.message);
        }else{
            var sql =
                `select * from patient where Medicalcard=${data[0].Medical_number} and name = '${data[0].name}'`;
            db.query(sql, [], (err, datas) => {
                if (err) {
                    console.log("出错了", err);
                    return res.send("错误" + err.message);
                } else {
                    var sql =
                        `select * from payfree where patient_id=${datas[0].patient_id} and ${req.query.statusFree==0?'status="待缴费"':'status!="待缴费"'}`;
                    db.query(sql, [], (err, dataes) => {
                        if (err) {
                            console.log("出错了", err);
                            return res.send("错误" + err.message);
                        } else {
                            const formattedUserDataArray = dataes.map(user => ({
                                ...user,
                                state: user.state === 1
                            }));
                            res.send({
                                dataes:formattedUserDataArray,
                                state:200
                            })
                        }
                    });
                }
            });
            
        }
    });
}

// 用户开单申请
exports.bingapply = ( req,res ) => {
    console.log(req.body)
    const { memberid , userid , medicine , inspect , test , subtotal } = req.body
    var sql =
        `select * from ${memberid==0?'applogin':'family'} where ${memberid==0?'user_id='+userid:'member_id='+memberid}`;
    db.query(sql, [], (err, data) => {
        if (err) {
            console.log("出错了", err);
            return res.send("错误" + err.message);
        }else{
            var sql =
                `select * from patient where Medicalcard=${data[0].Medical_number} and name = '${data[0].name}'`;
            db.query(sql, [], (err, datas) => {
                if (err) {
                    console.log("出错了", err);
                    return res.send("错误" + err.message);
                } else{
                    if(datas.length){
                        var sql =
                            `insert into billingrecord(patient_id,medicine,inspect,test,subtotal,statue) value(${datas[0].patient_id},'${JSON.stringify(medicine)}','${JSON.stringify(inspect)}','${JSON.stringify(test)}','${subtotal}','待审核')`;
                        db.query(sql, [], (err, data) => {
                            if (err) {
                                console.log("出错了", err);
                                return res.send("错误" + err.message);
                            } else {
                                res.send({
                                    data,
                                    patientid:datas[0].patient_id,
                                    state: 200
                                })
                            }
                        });
                    }else{
                        res.send({
                            datas,
                            state:404
                        })
                    }
                }
                // console.log(datas[0].patient_id)
                // res.send(datas)
                
                // var sql =
                //     `select * from billingrecord where patient_id = ${datas[0].patient_id}`;
                // db.query(sql, [], (err, dataes) => {
                //     if (err) {
                //         console.log("出错了", err);
                //         return res.send("错误" + err.message);
                //     } else {
                //         if(dataes.length){

                //         }else{
                            
                //         }
                //         res.send({
                //             dataes,
                //             state: 200
                //         })
                //     }
                // });
            });
        }
    });
}
// 用户开单查询
exports.applyselect = (req,res) => {
    var sql =
        `select * from billingrecord where patient_id = ${req.query.patientid}`;
    db.query(sql, [], (err, dataes) => {
        if (err) {
            console.log("出错了", err);
            return res.send("错误" + err.message);
        } else {
            res.send({
                dataes,
                state: 200
            })
        }
    });
}
// 用户开单查询
exports.applyselectreacord = (req,res) => {
    var sql =
        `select * from billingrecord where record_id = ${req.query.record_id}`;
    db.query(sql, [], (err, dataes) => {
        if (err) {
            console.log("出错了", err);
            return res.send("错误" + err.message);
        } else {
            res.send({
                dataes,
                state: 200
            })
        }
    });
}
// 开单状态修改
exports.appchangestate = (req,res) => {
    const { status , record_id } = req.body
    var sql =
        `update billingrecord set statue = '${status}' where record_id = ${record_id}`;
    db.query(sql, [], (err, dataes) => {
        if (err) {
            console.log("出错了", err);
            return res.send("错误" + err.message);
        } else {
            res.send({
                dataes,
                state: 200
            })
        }
    });
}
// 支付时间修改
exports.appchangetime = (req,res) => {
    const { record_id } = req.body
    var sql =
        `update billingrecord set paytime = '${new Date().getFullYear()+'-'+String(new Date().getMonth() + 1).padStart(2, '0')+'-'+String(new Date().getDate()).padStart(2, '0')+' '+String(new Date().getHours()).padStart(2, '0')+':'+String(new Date().getMinutes()).padStart(2, '0')+':'+String(new Date().getSeconds()).padStart(2, '0')}' where record_id = ${record_id}`;
    db.query(sql, [], (err, data) => {
        if (err) {
            console.log("出错了", err);
            return res.send("错误" + err.message);
        } else {
            res.send({
                data,
                state: 200
            })
        }
    });
}



// 就诊人切换查询patientid
exports.appselectpatientid = (req,res) => {
    const { memberid , userid } = req.query
    var sql =
        `select * from ${memberid==0?'applogin':'family'} where ${memberid==0?'user_id='+userid:'member_id='+memberid}`;
    db.query(sql, [], (err, data) => {
        if (err) {
            console.log("出错了", err);
            return res.send("错误" + err.message);
        }else{
            var sql =
                `select * from patient where Medicalcard=${data[0].Medical_number} and name = '${data[0].name}'`;
            db.query(sql, [], (err, datas) => {
                if (err) {
                    console.log("出错了", err);
                    return res.send("错误" + err.message);
                }
                res.send({
                    datas,
                    state:200
                })
            });
        }
    });
}
// 根据状态查询开单记录列表
exports.appselectstatuslist = (req,res) => {
    const { patientid , status } = req.query
    if(status==2){
        var sql =
            `select * from billingrecord where patient_id=${patientid} and statue = "审核通过" OR patient_id=${patientid} AND statue = "审核驳回"`
    }else{
        var sql =
            `select * from billingrecord where patient_id=${patientid} ${status==0?'':`and statue = '${status==1?'待审核':'已取消'}'`} `;
    }
    
    db.query(sql, [], (err, data) => {
        if (err) {
            console.log("出错了", err);
            return res.send("错误" + err.message);
        } else {
            res.send({
                data,
                state: 200
            })
        }
    });
}
//自助取号

// 查询取号信息
exports.appselectoffnum = (req,res) => {
    var sql =
        `select * from offernum where patient_id=${req.query.patient_id} and status = '待取号'`;
    db.query(sql, [], (err, data) => {
        if (err) {
            console.log("出错了", err);
            return res.send("错误" + err.message);
        } else {
            res.send({
                data,
                state:200
            })
        }
    });
}
// 查询已取号复诊信息
exports.appselectreturn = (req,res) => {
    var sql =
        `select * from offernum where patient_id=${req.query.patient_id} and status = '已取号'`;
    db.query(sql, [], (err, data) => {
        if (err) {
            console.log("出错了", err);
            return res.send("错误" + err.message);
        } else {
            res.send({
                data,
                state:200
            })
        }
    });
}
// 根据状态查询取号信息
exports.appoffnumstatus = (req,res) => {
    var sql =
        `select * from offernum where patient_id=${req.query.patient_id} and status = '${req.query.status}'`;
    db.query(sql, [], (err, data) => {
        if (err) {
            console.log("出错了", err);
            return res.send("错误" + err.message);
        } else {
            res.send({
                data,
                state:200
            })
        }
    });
}
// 取号详情查询
exports.appofferdetail = (req,res) => {
    var sql =
        `select * from offernum where offernumber_id=${req.query.offernumber_id}`;
    db.query(sql, [], (err, data) => {
        if (err) {
            console.log("出错了", err);
            return res.send("错误" + err.message);
        } else {
            res.send({
                data,
                state:200
            })
        }
    });
}
// 取号操作
exports.appoffernum = (req,res) => {
    var sql =
        `update offernum set status = '已取号' , offercode=20 where offernumber_id=${req.body.offernumber_id}`;
    db.query(sql, [], (err, data) => {
        if (err) {
            console.log("出错了", err);
            return res.send("错误" + err.message);
        } else {
            res.send({
                data,
                state:200
            })
        }
    });
}
// 取号列表新增
exports.appoffernuminsert = (req,res) => {
    const { avator , name , call , depart , patient , patient_id , registortime } = req.body
    var sql =
        'INSERT INTO offernum (patient_id, avator, name, '+'`call`'+`, depart, campus, patient, registortime, status) VALUES ( ${patient_id}, '${avator}', '${name}', '${call}', '${depart}', '四川省保健院南苑', '${patient}', '${registortime}', '待取号');`;
    db.query(sql, [], (err, dataes) => {
        if (err) {
            console.log("出错了", err);
            return res.send("错误" + err.message);
        } else {
            res.send({
                dataes,
                state:200
            })
        }
    });
}

// 根据患者id查询挂号信息
exports.appselectregister = (req,res) => {
    var sql =
        "select * from registerlist where patient_id=" + req.query.patient_id;
    db.query(sql, [], (err, dataes) => {
        if (err) {
            console.log("出错了", err);
            return res.send("错误" + err.message);
        } else {
            res.send({
                dataes,
                state:200
            })
        }
    });
}

// 医技预约查询待预约列表
exports.pendingappointment = (req, res) => {
    var sql =
        "select * from medical_technology where patinetid=" + req.query.patient_id;
    db.query(sql, [], (err, dataes) => {
        if (err) {
            console.log("出错了", err);
            return res.send("错误" + err.message);
        } else {
            res.send({
                dataes,
                state: 200
            })
        }
    });
}
// 医技预约列表查询
exports.pendingappointmentlist = (req, res) => {
    var sql =
        "select * from medical_technology where register_id=" + req.query.id;
    db.query(sql, [], (err, dataes) => {
        if (err) {
            console.log("出错了", err);
            return res.send("错误" + err.message);
        } else {
            res.send({
                dataes,
                state: 200
            })
        }
    });
}
// 取消预约
exports.pendingappointmentclose = (req, res) => {
    var sql =
        `update medical_technology set  status = '已取消' where register_id = ${req.body.register_id}`
    db.query(sql, [], (err, dataes) => {
        if (err) {
            console.log("出错了", err);
            return res.send("错误" + err.message);
        } else {
            res.send({
                dataes,
                state: 200
            })
        }
    });
}
// 医技预约新增记录
exports.pendingappointmentadd = (req, res) => {
    const { patient_id , patient , project , consult , time , status} = req.body
    var sql =
        `INSERT INTO medical_technology ( patinetid, test_item, patient, consult, register_time, status) VALUES (${patient_id}, '${project} ', '${patient}', '${consult}', '${time}', '${status}');
`;
    db.query(sql, [], (err, dataes) => {
        if (err) {
            console.log("出错了", err);
            return res.send("错误" + err.message);
        } else {
            res.send({
                dataes,
                state: 200
            })
        }
    });
}
// 医技预约预约
exports.pendingappointmentupdate = (req, res) => {
    const { register_id , consult , time , status} = req.body
    var sql =
        `update medical_technology set  consult = '${consult}' , register_time = '${time}' , status = '${status}' where register_id = ${register_id}`;
    db.query(sql, [], (err, dataes) => {
        if (err) {
            console.log("出错了", err);
            return res.send("错误" + err.message);
        } else {
            res.send({
                dataes,
                state: 200
            })
        }
    });
}